<template>
  <div class="schedule-page">
    <div class="breadcrumb-container">
      <el-breadcrumb :separator-icon="ArrowRight" class="breadcrumb-nav">
        <el-breadcrumb-item :to="{ path: '/' }" class="breadcrumb-item">
          <el-icon class="breadcrumb-icon"><HomeFilled /></el-icon>
          <span>主页</span>
        </el-breadcrumb-item>
        <el-breadcrumb-item class="breadcrumb-item">
          <el-icon class="breadcrumb-icon"><Setting /></el-icon>
          <span>产能管理</span>
        </el-breadcrumb-item>
        <el-breadcrumb-item class="breadcrumb-item active">
          <el-icon class="breadcrumb-icon"><Calendar /></el-icon>
          <span>生产排产</span>
        </el-breadcrumb-item>
      </el-breadcrumb>
    </div>

    <el-card class="content-card" shadow="never">
      <template #header>
        <div class="card-header">
          <span>生产排产</span>
        </div>
      </template>

      <!-- 基础信息 -->
      <div class="section">
        <div class="section-title">基础信息</div>
        <el-form :model="form" :rules="rules" ref="formRef" label-width="140px" class="form-container">
          <el-row :gutter="24">
            <!-- 左列 -->
            <el-col :span="12">
              <el-form-item label="工单编号">
                <el-input v-model="workOrderInfo.workOrderCode" disabled />
              </el-form-item>
              <el-form-item label="关联计划">
                <el-input v-model="workOrderInfo.planName" disabled />
              </el-form-item>
              <el-form-item label="类型">
                <el-input :value="sourceTypeName" disabled />
              </el-form-item>
              <el-form-item label="产品编号">
                <el-input v-model="workOrderInfo.productCode" disabled />
              </el-form-item>
              <el-form-item label="产品类型">
                <el-input :value="productTypeName" disabled />
              </el-form-item>
              <el-form-item label="BOM">
                <el-input v-model="workOrderInfo.bomCode" disabled />
              </el-form-item>
              <el-form-item label="* 计划数量" prop="planQuantity">
                <el-input-number
                  v-model="form.planQuantity"
                  :min="1"
                  :precision="0"
                  placeholder="请输入"
                  style="width: 100%"
                />
              </el-form-item>
              <el-form-item label="* 计划完工时间" prop="planEndTime">
                <el-date-picker
                  v-model="form.planEndTime"
                  type="datetime"
                  placeholder="请选择时间"
                  style="width: 100%"
                  format="YYYY-MM-DD HH:mm:ss"
                  value-format="YYYY-MM-DD HH:mm:ss"
                />
              </el-form-item>
              <el-form-item label="备注">
                <el-input v-model="form.remark" type="textarea" :rows="3" placeholder="请输入" />
              </el-form-item>
            </el-col>
            <!-- 右列 -->
            <el-col :span="12">
              <el-form-item label="工单名称">
                <el-input v-model="workOrderInfo.workOrderName" disabled />
              </el-form-item>
              <el-form-item label="计划编号">
                <el-input v-model="workOrderInfo.planCode" disabled />
              </el-form-item>
              <el-form-item label="产品名称">
                <el-input v-model="workOrderInfo.productName" disabled />
              </el-form-item>
              <el-form-item label="规格型号">
                <el-input v-model="workOrderInfo.productModel" disabled />
              </el-form-item>
              <el-form-item label="单位">
                <el-input v-model="workOrderInfo.productUnit" disabled />
              </el-form-item>
              <el-form-item label="版本">
                <el-input v-model="workOrderInfo.version" disabled />
              </el-form-item>
              <el-form-item label="* 计划开工时间" prop="planStartTime">
                <el-date-picker
                  v-model="form.planStartTime"
                  type="datetime"
                  placeholder="请选择时间"
                  style="width: 100%"
                  format="YYYY-MM-DD HH:mm:ss"
                  value-format="YYYY-MM-DD HH:mm:ss"
                />
              </el-form-item>
              <el-form-item label="需求日期">
                <el-date-picker
                  v-model="form.demandDate"
                  type="date"
                  placeholder="请选择日期"
                  style="width: 100%"
                  format="YYYY-MM-DD"
                  value-format="YYYY-MM-DD"
                />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>

      <!-- 物料清单 -->
      <div class="section">
        <div class="section-title">物料清单</div>
        <el-table :data="materialList" border stripe>
          <el-table-column type="index" label="序号" width="70" align="center" />
          <el-table-column prop="materialCode" label="物料编号" min-width="140" />
          <el-table-column prop="materialName" label="物料名称" min-width="160" />
          <el-table-column prop="specification" label="规格型号" min-width="140" />
          <el-table-column prop="unit" label="单位" width="100" align="center" />
          <el-table-column prop="estimatedUsage" label="预计使用量" width="120" align="center" />
          <el-table-column prop="materialRatio" label="用料比例" width="120" align="center">
            <template #default="scope">{{ scope.row.materialRatio }}%</template>
          </el-table-column>
        </el-table>
        <div class="material-summary">物料总量: {{ totalMaterialQuantity }}</div>
      </div>

      <!-- 工艺流程 -->
      <div class="section">
        <div class="section-title">工艺流程</div>
        <el-form label-width="140px">
          <el-form-item label="工艺路线名称">
            <el-input v-model="processRouteInfo.processRouteName" disabled />
          </el-form-item>
          <el-form-item label="工艺路线编号">
            <el-input v-model="processRouteInfo.processRouteCode" disabled />
          </el-form-item>
        </el-form>

        <div class="process-nodes">
          <div
            v-for="(node, index) in processNodes"
            :key="node.processNodeId"
            class="process-node-item"
            :class="{ active: activeNodeIndex === index }"
            @click="handleNodeClick(index)"
          >
            {{ index + 1 }} {{ node.processName }}
            <span v-if="index === processNodes.length - 1">★</span>
          </div>
        </div>

        <div v-if="activeNodeIndex >= 0 && processNodes[activeNodeIndex]" class="process-tasks">
          <div class="task-toolbar">
            <el-button type="primary" size="small">新增</el-button>
            <el-button size="small">编辑</el-button>
            <el-button type="danger" size="small">删除</el-button>
          </div>
          <el-table :data="taskList" border stripe>
            <el-table-column type="selection" width="48" />
            <el-table-column type="index" label="序号" width="70" align="center" />
            <el-table-column prop="taskCode" label="任务编号" min-width="140" />
            <el-table-column prop="taskName" label="任务名称" min-width="160" />
            <el-table-column prop="siteName" label="站点名称" min-width="140" />
            <el-table-column prop="siteCode" label="站点编号" min-width="140" />
            <el-table-column prop="planQuantity" label="计划数量" width="120" align="center" />
            <el-table-column prop="planStartTime" label="计划开工时间" min-width="160">
              <template #default="scope">
                {{ scope.row.planStartTime || '-' }}
              </template>
            </el-table-column>
            <el-table-column prop="planEndTime" label="计划完工时间" min-width="160">
              <template #default="scope">
                {{ scope.row.planEndTime || '-' }}
              </template>
            </el-table-column>
            <el-table-column label="任务颜色" width="100" align="center">
              <template #default="scope">
                <div
                  class="color-box"
                  :style="{ backgroundColor: scope.row.taskColor || '#409EFF' }"
                ></div>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="120" align="center">
              <template #default="scope">
                <el-button type="primary" link @click="handleViewMaterial(scope.row)">查看物料</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>

      <div class="footer-actions">
        <el-button @click="handleClose">关闭</el-button>
        <el-button type="primary" :loading="submitting" @click="handleSubmit">确定</el-button>
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ArrowRight, Calendar, HomeFilled, Setting } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { computed, onMounted, reactive, ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import type { FormInstance, FormRules } from 'element-plus'
import https from '@/Http/http'
import { extractPayload, getErrorMessage, getResponseMessage, isRequestSuccess } from '@/utils/responseHelper'

interface WorkOrderInfo {
  workOrderCode: string
  workOrderName: string
  planName: string
  planCode: string
  sourceType: number
  productName: string
  productCode: string
  productTypeId: number
  productModel?: string
  productUnit?: string
  bomCode?: string
  version?: string
}

interface MaterialItem {
  id: number
  materialCode: string
  materialName: string
  specification?: string
  unit?: string
  estimatedUsage: number
  materialRatio: number
}

interface ProcessNode {
  processNodeId: number
  processNodeCode: string
  processId: number
  processName: string
  processCode?: string
  color?: string
}

interface TaskItem {
  id: number
  taskCode: string
  taskName: string
  siteName: string
  siteCode?: string
  planQuantity: number
  planStartTime?: string
  planEndTime?: string
  taskColor?: string
}

const route = useRoute()
const router = useRouter()
const formRef = ref<FormInstance>()
const submitting = ref(false)
const loading = ref(false)

const workOrderId = computed(() => Number(route.query.id) || 0)

const workOrderInfo = reactive<WorkOrderInfo>({
  workOrderCode: '',
  workOrderName: '',
  planName: '',
  planCode: '',
  sourceType: 0,
  productName: '',
  productCode: '',
  productTypeId: 0,
  productModel: '',
  productUnit: '',
  bomCode: '',
  version: ''
})

const form = reactive({
  planQuantity: 0,
  planStartTime: '',
  planEndTime: '',
  demandDate: '',
  remark: ''
})

const rules: FormRules = {
  planQuantity: [{ required: true, message: '请输入计划数量', trigger: 'blur' }],
  planStartTime: [{ required: true, message: '请选择计划开工时间', trigger: 'change' }],
  planEndTime: [{ required: true, message: '请选择计划完工时间', trigger: 'change' }]
}

const materialList = ref<MaterialItem[]>([])
const processRouteInfo = reactive({
  processRouteCode: '',
  processRouteName: ''
})
const processNodes = ref<ProcessNode[]>([])
const activeNodeIndex = ref(-1)
const taskList = ref<TaskItem[]>([])

const sourceTypeName = computed(() => {
  const names: Record<number, string> = {
    1: '销售订单',
    2: '库存备货',
    3: '其他'
  }
  return names[workOrderInfo.sourceType] ?? '未知'
})

const productTypeName = computed(() => {
  // 这里可以根据productTypeId查询产品类型名称
  return '半成品'
})

const totalMaterialQuantity = computed(() => {
  return materialList.value.reduce((sum, item) => sum + Number(item.estimatedUsage), 0)
})

const loadWorkOrderDetail = async () => {
  loading.value = true
  try {
    let data: any = null
    
    if (workOrderId.value) {
      try {
        const response = await https.Reads.get('/AShow/WorkOrderDetail', {
          params: { workOrderId: workOrderId.value }
        })
        const payload = extractPayload(response)
        if (isRequestSuccess(payload)) {
          data = payload?.data ?? payload?.Data
        }
      } catch (error) {
        console.warn('获取工单详情失败，使用示例数据:', error)
      }
    }

    // 如果没有API数据，使用示例数据（根据图片）
    if (!data) {
      data = {
        workOrderCode: 'SCGD0154151',
        workOrderName: '新产品工单',
        planName: '新产品生产计划',
        planCode: 'JHBH1245468',
        sourceType: 1,
        productName: '新产品一',
        productCode: 'CPBH15648',
        productTypeId: 1,
        productModel: '20*50*30',
        productUnit: '瓶',
        bomCode: 'BOM0215646',
        version: '1.2',
        planQuantity: 0,
        planStartTime: '',
        planEndTime: '',
        demandDate: '',
        remark: '',
        Materials: [
          { id: 1, materialCode: 'WL0235', materialName: '物料一', specification: '500*500*600', unit: 'kg', estimatedUsage: 30, materialRatio: 20 },
          { id: 2, materialCode: 'WL0235', materialName: '物料一', specification: '500*500*600', unit: 'kg', estimatedUsage: 30, materialRatio: 20 },
          { id: 3, materialCode: 'WL0235', materialName: '物料一', specification: '500*500*600', unit: 'kg', estimatedUsage: 30, materialRatio: 20 },
          { id: 5, materialCode: 'WL0235', materialName: '物料一', specification: '500*500*600', unit: 'kg', estimatedUsage: 30, materialRatio: 20 },
          { id: 6, materialCode: 'WL0235', materialName: '物料一', specification: '500*500*600', unit: 'kg', estimatedUsage: 30, materialRatio: 20 }
        ],
        ProcessRoute: {
          processRouteCode: 'GYLX05484',
          processRouteName: '新产品工艺路线',
          ProcessNodes: [
            { processNodeId: 1, processNodeCode: 'GX001', processId: 1, processName: '工序一', processCode: 'GX001' },
            { processNodeId: 2, processNodeCode: 'GX002', processId: 2, processName: '工序二', processCode: 'GX002' },
            { processNodeId: 3, processNodeCode: 'GX003', processId: 3, processName: '工序三', processCode: 'GX003' },
            { processNodeId: 4, processNodeCode: 'GX004', processId: 4, processName: '工序四', processCode: 'GX004' }
          ]
        }
      }
    }

    // 填充基础信息
    Object.assign(workOrderInfo, {
      workOrderCode: data.workOrderCode ?? '',
      workOrderName: data.workOrderName ?? '',
      planName: data.planName ?? '',
      planCode: data.planCode ?? '',
      sourceType: data.sourceType ?? 0,
      productName: data.productName ?? '',
      productCode: data.productCode ?? '',
      productTypeId: data.productTypeId ?? 0,
      productModel: data.productModel ?? '',
      productUnit: data.productUnit ?? '',
      bomCode: data.bomCode ?? '',
      version: data.version ?? ''
    })

    // 填充表单
    form.planQuantity = data.planQuantity ?? 0
    form.planStartTime = data.planStartTime ? formatDateTime(data.planStartTime) : ''
    form.planEndTime = data.planEndTime ? formatDateTime(data.planEndTime) : ''
    form.demandDate = data.demandDate ? formatDate(data.demandDate) : ''
    form.remark = data.remark ?? ''

    // 填充物料清单
    materialList.value = data.Materials ?? []

    // 填充工艺流程
    if (data.ProcessRoute) {
      processRouteInfo.processRouteCode = data.ProcessRoute.processRouteCode ?? ''
      processRouteInfo.processRouteName = data.ProcessRoute.processRouteName ?? ''
      processNodes.value = data.ProcessRoute.ProcessNodes ?? []
      if (processNodes.value.length > 0) {
        // 默认激活第二个工序（工序二）
        activeNodeIndex.value = 1
        loadTaskList(processNodes.value[1]!.processNodeId)
      }
    }
  } catch (error) {
    console.error('加载工单详情失败:', error)
  } finally {
    loading.value = false
  }
}

const loadTaskList = async (processNodeId: number) => {
  // 这里应该根据processNodeId加载任务列表
  // 如果API失败，使用示例数据（根据图片）
  try {
    // 可以在这里调用API获取任务列表
    // const response = await https.Reads.get('/AShow/ProcessNodeTasks', { params: { processNodeId } })
    // taskList.value = response.data ?? []
    
    // 使用示例数据
    if (processNodeId === 2) {
      // 工序二的任务列表
      taskList.value = [
        {
          id: 1,
          taskCode: 'RWBH',
          taskName: '任务二',
          siteName: '站点三',
          siteCode: 'zd0235',
          planQuantity: 60,
          planStartTime: '2025-11-30 21:22',
          planEndTime: '2025-11-30 21:22',
          taskColor: '#409EFF'
        },
        {
          id: 2,
          taskCode: 'RWBH',
          taskName: '任务二',
          siteName: '站点三',
          siteCode: 'zd0235',
          planQuantity: 60,
          planStartTime: '2025-11-30 21:22',
          planEndTime: '2025-11-30 21:22',
          taskColor: '#409EFF'
        },
        {
          id: 3,
          taskCode: 'RWBH',
          taskName: '任务二',
          siteName: '站点三',
          siteCode: 'zd0235',
          planQuantity: 60,
          planStartTime: '2025-11-30 21:22',
          planEndTime: '2025-11-30 21:22',
          taskColor: '#409EFF'
        }
      ]
    } else {
      taskList.value = []
    }
  } catch (error) {
    console.error('加载任务列表失败:', error)
    taskList.value = []
  }
}

const handleNodeClick = (index: number) => {
  activeNodeIndex.value = index
  if (processNodes.value[index]) {
    loadTaskList(processNodes.value[index]!.processNodeId)
  }
}

const handleViewMaterial = (task: TaskItem) => {
  ElMessage.info(`查看任务 ${task.taskCode} 的物料`)
}

const handleSubmit = async () => {
  if (!formRef.value) return

  await formRef.value.validate(async (valid) => {
    if (!valid) return

    if (new Date(form.planStartTime) > new Date(form.planEndTime)) {
      ElMessage.error('完工时间不能早于开工时间')
      return
    }

    submitting.value = true
    try {
      const response = await https.Writes.post('/AWrite/WorkOrderSchedule', {
        workOrderId: workOrderId.value,
        planQuantity: form.planQuantity,
        planStartTime: form.planStartTime,
        planEndTime: form.planEndTime,
        demandDate: form.demandDate || null,
        remark: form.remark
      })
      const payload = extractPayload(response)
      if (!isRequestSuccess(payload)) {
        throw new Error(getResponseMessage(payload, '排产失败'))
      }
      ElMessage.success(getResponseMessage(payload, '排产成功'))
      router.back()
    } catch (error) {
      ElMessage.error(getErrorMessage(error, '排产失败'))
    } finally {
      submitting.value = false
    }
  })
}

const handleClose = () => {
  router.back()
}

const formatDate = (value: string | Date) => {
  if (!value) return ''
  const date = new Date(value)
  if (Number.isNaN(date.getTime())) return ''
  const pad = (num: number) => `${num}`.padStart(2, '0')
  return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}`
}

const formatDateTime = (value: string | Date) => {
  if (!value) return ''
  const date = new Date(value)
  if (Number.isNaN(date.getTime())) return ''
  const pad = (num: number) => `${num}`.padStart(2, '0')
  return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`
}

onMounted(() => {
  loadWorkOrderDetail()
})
</script>

<style scoped>
.schedule-page {
  padding: 16px;
  min-height: 100%;
  box-sizing: border-box;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
}

.breadcrumb-container {
  margin-bottom: 16px;
  padding: 16px 20px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.15);
}

.breadcrumb-nav :deep(.el-breadcrumb__inner) {
  color: rgba(255, 255, 255, 0.9);
  font-weight: 500;
  display: inline-flex;
  align-items: center;
  gap: 6px;
}

.breadcrumb-item.active :deep(.el-breadcrumb__inner) {
  color: #fff;
  font-weight: 600;
}

.breadcrumb-icon {
  font-size: 16px;
  margin-right: 4px;
}

.content-card {
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.08);
}

.card-header {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
}

.section {
  margin-bottom: 32px;
}

.section-title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 16px;
  padding-bottom: 8px;
  border-bottom: 2px solid #409EFF;
}

.form-container {
  max-width: 1200px;
}

.material-summary {
  margin-top: 12px;
  text-align: right;
  font-weight: 600;
  color: #303133;
}

.process-nodes {
  display: flex;
  gap: 0;
  margin-bottom: 16px;
  border-bottom: 1px solid #ebeef5;
}

.process-node-item {
  padding: 8px 16px;
  border: none;
  border-bottom: 3px solid transparent;
  border-radius: 0;
  cursor: pointer;
  transition: all 0.3s;
  background: transparent;
  color: #909399;
  font-size: 14px;
}

.process-node-item:hover {
  color: #409EFF;
}

.process-node-item.active {
  color: #409EFF;
  border-bottom-color: #409EFF;
  font-weight: 600;
}

.task-toolbar {
  margin-bottom: 12px;
  display: flex;
  gap: 8px;
}

.color-box {
  width: 24px;
  height: 24px;
  border-radius: 4px;
  margin: 0 auto;
}

.footer-actions {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  margin-top: 32px;
  padding-top: 16px;
  border-top: 1px solid #ebeef5;
}
</style>

